package com.paipaideli.ui.mine.address;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.R;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.utils.JsonUtil;
import com.paipaideli.common.utils.JsutmentUtil;
import com.paipaideli.common.utils.StringUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.Utils;
import com.paipaideli.common.views.wheelview.bean.AddressDetailsEntity;
import com.paipaideli.common.views.wheelview.bean.AddressModel;
import com.paipaideli.common.views.wheelview.weight.wheel.ChooseAddressWheel;
import com.paipaideli.common.views.wheelview.weight.wheel.OnAddressChangeListener;
import com.paipaideli.ui.mine.order.OrderDetailActivity;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 添加修改收货地址
 */
public class ModifyAddressActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.text_choose_add)
    TextView text_choose_add;
    @BindView(R.id.rel_choose_add)
    RelativeLayout rel_choose_add;
    @BindView(R.id.imageview_add_ture)
    ImageView imageview_add_ture;
    @BindView(R.id.et_add_name)
    EditText etAddName;
    @BindView(R.id.et_add_phone)
    EditText etAddPhone;
    @BindView(R.id.et_add_infoadd)
    EditText etAddInfoadd;
    @BindView(R.id.btn_add_ok)
    Button btnAddOk;

    private ChooseAddressWheel chooseAddressWheel;
    private String add;
    private NewAddressEntity newAddressEntity;
    private boolean flag = true;
    private String which;
    private String id;
    private String name;
    private String phone;
    private String provice;
    private String city;
    private String area;
    private String postnum;
    private String address;

    @Override
    public int getContentView() {
        return R.layout.activity_modfiyadd;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        which = getIntent().getStringExtra("which");
        if (which.equals("1")) {
            top_title.setText("新增收货地址");
        } else {
            top_title.setText("编辑收货地址");
            id = getIntent().getStringExtra("id");
            name = getIntent().getStringExtra("name");
            etAddName.setText(name);
            phone = getIntent().getStringExtra("phone");
            etAddPhone.setText(phone);
            provice = getIntent().getStringExtra("province");
            city = getIntent().getStringExtra("city");
            area = getIntent().getStringExtra("area");
            add = provice + city + area;
            text_choose_add.setText(add);
            address = getIntent().getStringExtra("address");
            etAddInfoadd.setText(address);
            String isUse = getIntent().getStringExtra("isUse");
            if (isUse.equals("1")) {
                flag = true;
                imageview_add_ture.setBackgroundResource(R.mipmap.icon_address_ok);
            } else {
                flag = false;
                imageview_add_ture.setBackgroundResource(R.mipmap.icon_address_no);
            }
        }

        initWheel();
        initData();

        //省市县
        rel_choose_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseAddressWheel.show(view);
            }
        });


        //默认地址
        RxView.clicks(top_back).subscribe(o -> {
            finish();
        }, throwable -> {
        });


        //默认地址
        RxView.clicks(imageview_add_ture).subscribe(o -> {
            if (flag) {
                flag = false;
                imageview_add_ture.setBackgroundResource(R.mipmap.icon_address_no);
            } else {
                flag = true;
                imageview_add_ture.setBackgroundResource(R.mipmap.icon_address_ok);
            }
        }, throwable -> {
        });

        //收货地址
        addDisposable(RxView.clicks(btnAddOk)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
                    addAddress();
                }));

    }

    /**
     * 初始化地址
     */
    private void initWheel() {
        chooseAddressWheel = new ChooseAddressWheel(this);
        chooseAddressWheel.setOnAddressChangeListener(new OnAddressChangeListener() {
            @Override
            public void onAddressChange(String province, String citys, String district) {
                provice = province;
                city = citys;
                area = district;
                add = (province + " " + city + " " + district);
                text_choose_add.setText(add);
            }
        });
    }

    private void addAddress() {
        name = etAddName.getText().toString().trim();
        phone = etAddPhone.getText().toString().trim();
        address = etAddInfoadd.getText().toString().trim();
        if (!StringUtil.isEmpty(name)) {
            if (!StringUtil.isEmpty(phone)) {
                if (JsutmentUtil.isMobileTrue(phone)) {
                    if (!StringUtil.isEmpty(add)) {
                        if (!StringUtil.isEmpty(address)) {
                            JSONObject requestData = new JSONObject();
                            try {
                                if (which.equals("1")){
                                    requestData.put("id", "");
                                }else {
                                    requestData.put("id", id);
                                }
                                requestData.put("name", name);
                                requestData.put("phone", phone);
                                requestData.put("province", provice);
                                requestData.put("city", city);
                                requestData.put("area", area);
                                requestData.put("postcode", "");
                                requestData.put("address", address);
                                if (flag) {
                                    requestData.put("isUse", "1");
                                } else {
                                    requestData.put("isUse", "0");
                                }
                            } catch (Exception e) {
                                e.getMessage();
                            }
                            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
                            if (which.equals("1")) {//新增
                                Api.getInstanceGson().addAddress(body)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(request -> {
                                            if (request.getCode().equals("200")) {
                                                finish();
                                                ToastUtil.show(request.getMessage());
                                            } else {
                                                ToastUtil.show(request.getMessage());
                                            }
                                        }, throwable -> {
                                            Log.e(TAG, "error", throwable);
                                        });
                            } else {//编辑
                                Api.getInstanceGson().updateAddress(body)
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(request -> {
                                            if (request.getCode().equals("200")) {
                                                finish();
                                                ToastUtil.show(request.getMessage());
                                            } else {
                                                ToastUtil.show(request.getMessage());
                                            }
                                        }, throwable -> {
                                            Log.e(TAG, "error", throwable);
                                        });
                            }
                        } else {
                            ToastUtil.show("请输入详细的收货地址");
                        }
                    } else {
                        ToastUtil.show("请选择当前的省市县");
                    }
                } else {
                    ToastUtil.show("请输入正确的手机号码");
                }
            } else {
                ToastUtil.show("请输入收货人手机号码");
            }
        } else {
            ToastUtil.show("请输入收货人姓名");
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        String address = Utils.readAssert(this, "address.txt");
        AddressModel model = JsonUtil.parseJson(address, AddressModel.class);
        if (model != null) {
            AddressDetailsEntity data = model.Result;
            if (data == null) return;
            if (data.ProvinceItems != null && data.ProvinceItems.Province != null) {
                chooseAddressWheel.setProvince(data.ProvinceItems.Province);
                chooseAddressWheel.defaultValue(data.Province, data.City, data.Area);
            }
        }
    }
}
